#!/usr/bin/env python

import sys
import os


if len(sys.argv) not in [2,3]:
	print "give one .glade as input, will print output to stdout"
	print "if a second parameter (a c file) is given, uses it to tell which functions need to be added"
	print "ex : glade_to_callbacks.py gladefile.glade callbacks.c"
else:
	a = open(sys.argv[1],"r")
	b = None
	if len(sys.argv) == 3 and (sys.argv[2].endswith(".h") or sys.argv[2].endswith(".c")):
		b = open(sys.argv[2],"r")
		if not b:
			print "couldn't open file",sys.argv[2],"not using it"
		else:
			cfile = b.read()
			b.close()
	if not a:
		print "couldn't open file",sys.argv[1]
	else:
		lines = a.read()
		a.close()
		txt = "handler=\""
		protos = []
		while txt in lines:
			start = lines.find(txt)
			end = lines.find('"',start+len(txt))
			callback = lines[start+len(txt):end]
			found_in_c_file = b and callback in cfile
			if not callback == "gtk_main_quit" and not found_in_c_file:
				to_add = "void "+callback+" (GtkWidget* emitter, gpointer on_data);"
				protos.append(to_add)
				print to_add
			lines = lines[0:start]+lines[end+1:]
		for a in protos:
			print a[0:-1]+"\n{\n}"
		print "done"